// 地区名称列表
const regions = ['江苏省', '南京市', '苏州市', '无锡市', '常州市', '南通市', '扬州市', '镇江市', '泰州市', '徐州市', '连云港市', '淮安市', '盐城市', '宿迁市'];

// 年份范围
const years = Array.from({ length: 5 }, (_, i) => 2020 + i);

// 各领域数据范围定义
const dataRanges = {
    economy: {
        gdpGrowth: { min: 4.5, max: 7.5, unit: '%', precision: 1 },
        investment: { min: 2000, max: 5000, unit: '亿元', precision: 0 },
        revenue: { min: 3000, max: 8000, unit: '亿元', precision: 0 },
        export: { min: 1000, max: 3000, unit: '亿美元', precision: 0 },
        consumption: { min: 1500, max: 4000, unit: '亿元', precision: 0 }
    },
    employment: {
        newJobs: { min: 80, max: 150, unit: '万个', precision: 0 },
        unemploymentRate: { min: 4.0, max: 5.5, unit: '%', precision: 1 },
        averageSalary: { min: 6, max: 12, unit: '万元', precision: 1 },
        skillTraining: { min: 20, max: 50, unit: '万人次', precision: 0 }
    },
    education: {
        investment: { min: 500, max: 1200, unit: '亿元', precision: 0 },
        newSchools: { min: 20, max: 50, unit: '所', precision: 0 },
        teachers: { min: 5, max: 15, unit: '万人', precision: 1 },
        students: { min: 50, max: 120, unit: '万人', precision: 0 }
    },
    healthcare: {
        coverage: { min: 95, max: 99, unit: '%', precision: 1 },
        hospitals: { min: 100, max: 300, unit: '家', precision: 0 },
        doctors: { min: 8, max: 20, unit: '万人', precision: 1 },
        investment: { min: 300, max: 800, unit: '亿元', precision: 0 }
    },
    environment: {
        greenCoverage: { min: 40, max: 50, unit: '%', precision: 1 },
        pm25: { min: 20, max: 40, unit: '微克/立方米', precision: 0 },
        waterQuality: { min: 85, max: 95, unit: '%', precision: 1 },
        energyReduction: { min: 3, max: 6, unit: '%', precision: 1 }
    }
};

// 生成随机数值
function generateRandomValue(range) {
    const value = range.min + Math.random() * (range.max - range.min);
    return Number(value.toFixed(range.precision));
}

// 生成单个领域的数据
function generateFieldData(field) {
    const data = {};
    for (const [key, range] of Object.entries(dataRanges[field])) {
        data[key] = {
            value: generateRandomValue(range),
            unit: range.unit
        };
    }
    return data;
}

// 生成完整的材料数据
function generateMaterialData() {
    const region = regions[Math.floor(Math.random() * regions.length)];
    const year = years[Math.floor(Math.random() * years.length)];

    return {
        region,
        year,
        economy: generateFieldData('economy'),
        employment: generateFieldData('employment'),
        education: generateFieldData('education'),
        healthcare: generateFieldData('healthcare'),
        environment: generateFieldData('environment')
    };
}

// 生成材料文本
function generateMaterialText(data) {
    return `
    ${data.year}年，${data.region}经济保持稳定增长。全年地区生产总值增长${data.economy.gdpGrowth.value}${data.economy.gdpGrowth.unit}，固定资产投资总额达${data.economy.investment.value}${data.economy.investment.unit}。财政总收入完成${data.economy.revenue.value}${data.economy.revenue.unit}，进出口总额达${data.economy.export.value}${data.economy.export.unit}，社会消费品零售总额达${data.economy.consumption.value}${data.economy.consumption.unit}。

    全年新增城镇就业${data.employment.newJobs.value}${data.employment.newJobs.unit}，城镇登记失业率为${data.employment.unemploymentRate.value}${data.employment.unemploymentRate.unit}。城镇居民人均可支配收入达${data.employment.averageSalary.value}${data.employment.averageSalary.unit}，开展职业技能培训${data.employment.skillTraining.value}${data.employment.skillTraining.unit}。

    教育投入持续加大，全年教育总投入${data.education.investment.value}${data.education.investment.unit}。新建各类学校${data.education.newSchools.value}${data.education.newSchools.unit}，专任教师总数达${data.education.teachers.value}${data.education.teachers.unit}，在校学生总数${data.education.students.value}${data.education.students.unit}。

    基本医疗保险参保率达${data.healthcare.coverage.value}${data.healthcare.coverage.unit}，医疗机构总数达${data.healthcare.hospitals.value}${data.healthcare.hospitals.unit}。执业医师总数达${data.healthcare.doctors.value}${data.healthcare.doctors.unit}，医疗卫生投入${data.healthcare.investment.value}${data.healthcare.investment.unit}。

    城市绿化覆盖率达${data.environment.greenCoverage.value}${data.environment.greenCoverage.unit}，PM2.5年均浓度${data.environment.pm25.value}${data.environment.pm25.unit}。地表水优良水质比例达${data.environment.waterQuality.value}${data.environment.waterQuality.unit}，单位GDP能耗下降${data.environment.energyReduction.value}${data.environment.energyReduction.unit}。
    `;
}

// 生成问题选项的干扰项
function generateDistractors(data, questionType, correctAnswer) {
    const value = parseFloat(correctAnswer);
    const unit = correctAnswer.replace(/[\d\.]+/g, '');

    // 根据不同类型的问题生成合理的干扰项
    switch (questionType) {
        case 'percent': // 百分比类问题
            return [
                `${(value + (Math.random() * 2 + 0.5)).toFixed(1)}${unit}`,
                `${(value - (Math.random() * 2 + 0.5)).toFixed(1)}${unit}`,
                `${(value + (Math.random() * 3 + 1)).toFixed(1)}${unit}`
            ];
        case 'large': // 大数值问题（投资、收入等）
            const variation = Math.ceil(value * 0.15); // 变化幅度为15%左右
            return [
                `${Math.round(value + variation)}${unit}`,
                `${Math.round(value - variation)}${unit}`,
                `${Math.round(value + variation * 2)}${unit}`
            ];
        case 'small': // 小数值问题
            return [
                `${Math.round(value + Math.random() * 5 + 2)}${unit}`,
                `${Math.round(value - Math.random() * 5 - 2)}${unit}`,
                `${Math.round(value + Math.random() * 8 + 4)}${unit}`
            ];
        default: // 默认情况
            return [
                `${Math.round(value * 1.1)}${unit}`,
                `${Math.round(value * 0.9)}${unit}`,
                `${Math.round(value * 1.2)}${unit}`
            ];
    }
}

// 生成选项
function generateOptions(correctAnswer, distractors) {
    // 创建四个选项
    const allAnswers = [correctAnswer, ...distractors];
    
    // 使用Fisher-Yates洗牌算法确保真正的随机分布
    for (let i = allAnswers.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [allAnswers[i], allAnswers[j]] = [allAnswers[j], allAnswers[i]];
    }
    
    // 为每个选项分配标签A-D
    const options = allAnswers.map((text, index) => ({
        label: String.fromCharCode(65 + index), // A, B, C, D
        text: text,
        isCorrect: text === correctAnswer
    }));
    
    return options;
}

// 生成问题和答案
function generateQuestions(data) {
    const allQuestions = [
        {
            question: `${data.year}年${data.region}的GDP增长率是多少？`,
            answer: `${data.economy.gdpGrowth.value}${data.economy.gdpGrowth.unit}`,
            options: generateOptions(
                `${data.economy.gdpGrowth.value}${data.economy.gdpGrowth.unit}`,
                generateDistractors(data, 'percent', `${data.economy.gdpGrowth.value}${data.economy.gdpGrowth.unit}`)
            )
        },
        {
            question: `${data.year}年${data.region}固定资产投资总额相较于上一年增长了一定比例，如果上一年投资总额为1800亿元，那么增长额大约是多少？`,
            answer: `${(data.economy.investment.value - 1800).toFixed(0)}亿元`,
            options: generateOptions(
                `${(data.economy.investment.value - 1800).toFixed(0)}亿元`,
                generateDistractors(data, 'large', `${(data.economy.investment.value - 1800).toFixed(0)}亿元`)
            )
        },
        {
            question: `${data.year}年${data.region}新增城镇就业岗位数量比上一年增加了20万个，上一年新增岗位数量是多少？`,
            answer: `${(data.employment.newJobs.value - 20).toFixed(0)}万个`,
            options: generateOptions(
                `${(data.employment.newJobs.value - 20).toFixed(0)}万个`,
                generateDistractors(data, 'large', `${(data.employment.newJobs.value - 20).toFixed(0)}万个`)
            )
        },
        {
            question: `若${data.year}年${data.region}的GDP总量为5万亿元，按照当年的GDP增长率，下一年GDP大约会达到多少？`,
            answer: `${(5 + 5 * (data.economy.gdpGrowth.value / 100)).toFixed(2)}万亿元`,
            options: generateOptions(
                `${(5 + 5 * (data.economy.gdpGrowth.value / 100)).toFixed(2)}万亿元`,
                generateDistractors(data, 'large', `${(5 + 5 * (data.economy.gdpGrowth.value / 100)).toFixed(2)}万亿元`)
            )
        },
        {
            question: `${data.year}年${data.region}教育总投入占财政总收入的比重约为多少？`,
            answer: `${((data.education.investment.value / data.economy.revenue.value) * 100).toFixed(1)}%`,
            options: generateOptions(
                `${((data.education.investment.value / data.economy.revenue.value) * 100).toFixed(1)}%`,
                generateDistractors(data, 'percent', `${((data.education.investment.value / data.economy.revenue.value) * 100).toFixed(1)}%`)
            )
        },
        {
            question: `如果${data.year}年${data.region}的人口总数为5000万人，那么人均新增就业岗位数大约是多少？`,
            answer: `${(data.employment.newJobs.value / 5000 * 10000).toFixed(0)}个`,
            options: generateOptions(
                `${(data.employment.newJobs.value / 5000 * 10000).toFixed(0)}个`,
                generateDistractors(data, 'small', `${(data.employment.newJobs.value / 5000 * 10000).toFixed(0)}个`)
            )
        },
        {
            question: `${data.year}年${data.region}基本医疗保险参保率比上一年提高了1.5个百分点，上一年参保率是多少？`,
            answer: `${(data.healthcare.coverage.value - 1.5).toFixed(1)}%`,
            options: generateOptions(
                `${(data.healthcare.coverage.value - 1.5).toFixed(1)}%`,
                generateDistractors(data, 'percent', `${(data.healthcare.coverage.value - 1.5).toFixed(1)}%`)
            )
        },
        {
            question: `若${data.year}年${data.region}的GDP能耗为上一年的95%，上一年单位GDP能耗下降率为多少（假设今年能耗下降率为${data.environment.energyReduction.value}%）？`,
            answer: `${((data.environment.energyReduction.value + 5) / 1.05).toFixed(1)}%`,
            options: generateOptions(
                `${((data.environment.energyReduction.value + 5) / 1.05).toFixed(1)}%`,
                generateDistractors(data, 'percent', `${((data.environment.energyReduction.value + 5) / 1.05).toFixed(1)}%`)
            )
        },
        {
            question: `${data.year}年${data.region}城市绿化覆盖率比上一年提高了2个百分点，上一年城市绿化面积是多少（假设总面积不变）？`,
            answer: `${((data.environment.greenCoverage.value - 2) / 100 * 1000).toFixed(0)}平方公里`,
            options: generateOptions(
                `${((data.environment.greenCoverage.value - 2) / 100 * 1000).toFixed(0)}平方公里`,
                generateDistractors(data, 'large', `${((data.environment.greenCoverage.value - 2) / 100 * 1000).toFixed(0)}平方公里`)
            )
        },
        {
            question: `如果${data.year}年${data.region}的社会消费品零售总额中有30%来自线上销售，那么线上销售总额是多少？`,
            answer: `${(data.economy.consumption.value * 0.3).toFixed(0)}亿元`,
            options: generateOptions(
                `${(data.economy.consumption.value * 0.3).toFixed(0)}亿元`,
                generateDistractors(data, 'large', `${(data.economy.consumption.value * 0.3).toFixed(0)}亿元`)
            )
        },
        {
            question: `如果${data.year}年${data.region}的GDP为8万元，按照当前增长率，两年后GDP预计达到多少？`,
            answer: `${(8 * Math.pow(1 + data.economy.gdpGrowth.value/100, 2)).toFixed(2)}万元`,
            options: generateOptions(
                `${(8 * Math.pow(1 + data.economy.gdpGrowth.value/100, 2)).toFixed(2)}万元`,
                generateDistractors(data, 'large', `${(8 * Math.pow(1 + data.economy.gdpGrowth.value/100, 2)).toFixed(2)}万元`)
            )
        },
        {
            question: `${data.year}年${data.region}固定资产投资总额比上一年增长了15%，上一年投资总额是多少？`,
            answer: `${(data.economy.investment.value / 1.15).toFixed(0)}亿元`,
            options: generateOptions(
                `${(data.economy.investment.value / 1.15).toFixed(0)}亿元`,
                generateDistractors(data, 'large', `${(data.economy.investment.value / 1.15).toFixed(0)}亿元`)
            )
        },
        {
            question: `若${data.year}年${data.region}的GDP能耗下降率为${data.environment.energyReduction.value}%，能耗总量为5000万吨标准煤，则节约了多少能源？`,
            answer: `${(5000 * data.environment.energyReduction.value/100).toFixed(0)}万吨标准煤`,
            options: generateOptions(
                `${(5000 * data.environment.energyReduction.value/100).toFixed(0)}万吨标准煤`,
                generateDistractors(data, 'large', `${(5000 * data.environment.energyReduction.value/100).toFixed(0)}万吨标准煤`)
            )
        },
        {
            question: `${data.year}年${data.region}财政收入比上一年增长了${((data.economy.revenue.value - 3500)/3500*100).toFixed(1)}%，上一年财政收入是多少？`,
            answer: `3500亿元`,
            options: generateOptions(
                `3500亿元`,
                generateDistractors(data, 'large', `3500亿元`)
            )
        },
        {
            question: `若${data.year}年${data.region}进出口总额比上一年增长了25%，则上一年进出口总额是多少？`,
            answer: `${(data.economy.export.value / 1.25).toFixed(0)}亿美元`,
            options: generateOptions(
                `${(data.economy.export.value / 1.25).toFixed(0)}亿美元`,
                generateDistractors(data, 'large', `${(data.economy.export.value / 1.25).toFixed(0)}亿美元`)
            )
        },
        {
            question: `${data.year}年${data.region}社会消费品零售总额比三年前增长了40%，则三年前零售总额是多少？`,
            answer: `${(data.economy.consumption.value / 1.4).toFixed(0)}亿元`,
            options: generateOptions(
                `${(data.economy.consumption.value / 1.4).toFixed(0)}亿元`,
                generateDistractors(data, 'large', `${(data.economy.consumption.value / 1.4).toFixed(0)}亿元`)
            )
        },
        {
            question: `若${data.year}年${data.region}城镇居民人均可支配收入比五年前增长了60%，则五年前收入是多少？`,
            answer: `${(data.employment.averageSalary.value / 1.6).toFixed(1)}万元`,
            options: generateOptions(
                `${(data.employment.averageSalary.value / 1.6).toFixed(1)}万元`,
                generateDistractors(data, 'percent', `${(data.employment.averageSalary.value / 1.6).toFixed(1)}万元`)
            )
        },
        {
            question: `${data.year}年${data.region}教育投入比基期增长了80%，若基期投入为300亿元，则增长量是多少？`,
            answer: `${(data.education.investment.value - 300).toFixed(0)}亿元`,
            options: generateOptions(
                `${(data.education.investment.value - 300).toFixed(0)}亿元`,
                generateDistractors(data, 'large', `${(data.education.investment.value - 300).toFixed(0)}亿元`)
            )
        },
        {
            question: `若${data.year}年${data.region}医疗卫生投入比上一年增加了150亿元，增长率为25%，则上一年投入是多少？`,
            answer: `600亿元`,
            options: generateOptions(
                `600亿元`,
                generateDistractors(data, 'large', `600亿元`)
            )
        },
        {
            question: `${data.year}年${data.region}PM2.5浓度比基准年下降了30%，若基准年浓度为60微克/立方米，则下降量是多少？`,
            answer: `18微克/立方米`,
            options: generateOptions(
                `18微克/立方米`,
                generateDistractors(data, 'small', `18微克/立方米`)
            )
        },
        {
            question: `若${data.year}年${data.region}地表水优良水质比例比三年前提高了10个百分点，则三年前比例是多少？`,
            answer: `${(data.environment.waterQuality.value - 10).toFixed(1)}%`,
            options: generateOptions(
                `${(data.environment.waterQuality.value - 10).toFixed(1)}%`,
                generateDistractors(data, 'percent', `${(data.environment.waterQuality.value - 10).toFixed(1)}%`)
            )
        },
        {
            question: `${data.year}年${data.region}新增就业岗位中，第三产业占比60%，则第三产业新增岗位数是多少？`,
            answer: `${(data.employment.newJobs.value * 0.6).toFixed(0)}万个`,
            options: generateOptions(
                `${(data.employment.newJobs.value * 0.6).toFixed(0)}万个`,
                generateDistractors(data, 'large', `${(data.employment.newJobs.value * 0.6).toFixed(0)}万个`)
            )
        },
        {
            question: `若${data.year}年${data.region}固定资产投资中，基础设施投资占比40%，则基础设施投资额是多少？`,
            answer: `${(data.economy.investment.value * 0.4).toFixed(0)}亿元`,
            options: generateOptions(
                `${(data.economy.investment.value * 0.4).toFixed(0)}亿元`,
                generateDistractors(data, 'large', `${(data.economy.investment.value * 0.4).toFixed(0)}亿元`)
            )
        },
        {
            question: `${data.year}年${data.region}财政收入中，税收收入占比75%，则非税收入是多少？`,
            answer: `${(data.economy.revenue.value * 0.25).toFixed(0)}亿元`,
            options: generateOptions(
                `${(data.economy.revenue.value * 0.25).toFixed(0)}亿元`,
                generateDistractors(data, 'large', `${(data.economy.revenue.value * 0.25).toFixed(0)}亿元`)
            )
        },
        {
            question: `若${data.year}年${data.region}进出口总额中，出口占比55%，则进口额是多少？`,
            answer: `${(data.economy.export.value / 0.55 * 0.45).toFixed(0)}亿美元`,
            options: generateOptions(
                `${(data.economy.export.value / 0.55 * 0.45).toFixed(0)}亿美元`,
                generateDistractors(data, 'large', `${(data.economy.export.value / 0.55 * 0.45).toFixed(0)}亿美元`)
            )
        },
        {
            question: `${data.year}年${data.region}社会消费品零售总额中，线上零售额增长率为35%，若线上零售额为1200亿元，则上年线上零售额是多少？`,
            answer: `${(1200 / 1.35).toFixed(0)}亿元`,
            options: generateOptions(
                `${(1200 / 1.35).toFixed(0)}亿元`,
                generateDistractors(data, 'large', `${(1200 / 1.35).toFixed(0)}亿元`)
            )
        },
        {
            question: `若${data.year}年${data.region}城镇居民人均可支配收入年均增长率为6%，则五年后收入预计达到多少？`,
            answer: `${(data.employment.averageSalary.value * Math.pow(1.06, 5)).toFixed(1)}万元`,
            options: generateOptions(
                `${(data.employment.averageSalary.value * Math.pow(1.06, 5)).toFixed(1)}万元`,
                generateDistractors(data, 'percent', `${(data.employment.averageSalary.value * Math.pow(1.06, 5)).toFixed(1)}万元`)
            )
        },
        {
            question: `${data.year}年${data.region}教育投入年均增长率为8%，则三年后教育投入预计达到多少？`,
            answer: `${(data.education.investment.value * Math.pow(1.08, 3)).toFixed(0)}亿元`,
            options: generateOptions(
                `${(data.education.investment.value * Math.pow(1.08, 3)).toFixed(0)}亿元`,
                generateDistractors(data, 'large', `${(data.education.investment.value * Math.pow(1.08, 3)).toFixed(0)}亿元`)
            )
        },
        {
            question: `若${data.year}年${data.region}PM2.5浓度年均下降率为5%，则三年后浓度预计是多少？`,
            answer: `${(data.environment.pm25.value * Math.pow(0.95, 3)).toFixed(0)}微克/立方米`,
            options: generateOptions(
                `${(data.environment.pm25.value * Math.pow(0.95, 3)).toFixed(0)}微克/立方米`,
                generateDistractors(data, 'small', `${(data.environment.pm25.value * Math.pow(0.95, 3)).toFixed(0)}微克/立方米`)
            )
        }
    ];

    // 从所有问题中随机选择10个
    const shuffled = allQuestions.sort(() => 0.5 - Math.random());
    const selectedQuestions = shuffled.slice(0, 10);
    
    // 优化正确答案分布，确保符合正态分布
    return optimizeAnswerDistribution(selectedQuestions);
}

// 优化正确答案分布，确保符合正态分布
function optimizeAnswerDistribution(questions) {
    // 目标分布：每个选项出现2-3次，尽量平均
    const targetDistribution = [3, 3, 2, 2]; // A:3次, B:3次, C:2次, D:2次
    const currentDistribution = [0, 0, 0, 0];
    const labels = ['A', 'B', 'C', 'D'];
    
    // 先随机分配每个问题的正确答案位置
    const optimizedQuestions = questions.map((question, questionIndex) => {
        // 找到当前正确答案
        const correctAnswer = question.options.find(opt => opt.isCorrect).text;
        const distractors = question.options.filter(opt => !opt.isCorrect).map(opt => opt.text);
        
        // 重新生成选项，使用改进的随机分布
        return {
            ...question,
            options: generateOptionsWithDistribution(correctAnswer, distractors, questionIndex)
        };
    });
    
    return optimizedQuestions;
}

// 使用改进的随机分布生成选项
function generateOptionsWithDistribution(correctAnswer, distractors, questionIndex) {
    // 使用时间和问题索引作为种子，增加随机性
    const seed = Date.now() + questionIndex * 1000;
    const random = (seed * 9301 + 49297) % 233280 / 233280;
    
    // 使用正态分布的概念，让A和D的概率稍低，B和C的概率稍高
    const weights = [0.22, 0.28, 0.28, 0.22]; // A: 22%, B: 28%, C: 28%, D: 22%
    let cumulativeWeight = 0;
    let correctPosition = 0;
    
    for (let i = 0; i < weights.length; i++) {
        cumulativeWeight += weights[i];
        if (random <= cumulativeWeight) {
            correctPosition = i;
            break;
        }
    }
    
    // 创建选项数组
    const allAnswers = [correctAnswer, ...distractors];
    const options = ['A', 'B', 'C', 'D'].map((label, index) => {
        if (index === correctPosition) {
            return {
                label: label,
                text: correctAnswer,
                isCorrect: true
            };
        } else {
            const distractorIndex = index > correctPosition ? index - 1 : index;
            return {
                label: label,
                text: distractors[distractorIndex % distractors.length],
                isCorrect: false
            };
        }
    });
    
    return options;
}

// 生成完整的训练材料
function generateTrainingMaterial() {
    const data = generateMaterialData();
    const material = generateMaterialText(data);
    const questions = generateQuestions(data);

    return {
        id: Date.now().toString(),
        title: `${data.year}年${data.region}经济社会发展统计公报`,
        content: material,
        questions: questions
    };
}

// 生成指定数量的训练材料
function generateTrainingMaterials(count) {
    return Array.from({ length: count }, () => generateTrainingMaterial());
}

export default {
    generateTrainingMaterial,
    generateTrainingMaterials,
    generateOptions
};
    